<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

use addons\shopro\controller\Common;
use addons\shopro\service\order\OrderCreate;
use addons\shopro\service\order\OrderOper;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\Pay as PayModel;
use addons\shopro\library\express\Express as ExpressLib;
use app\admin\model\shopro\user\Coupon;

/**
 * 合并订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];
	protected $psts=[-1=>'已取消',0=>'待取件',1=>'待支付',2=>'待接单',3=>'待取件',4=>'运输中',5=>'已送达'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }
	//合并订单列表 配合计划任务使用
    public function getOrderList()
    {
        $po=$this->request->param();
		$page=$po['page']?:1;
		$current_page=$page;
		$page=$page>0?$page-1:0;
		$size=10;
		$limit=' limit '.$page*$size.','.$size.' ';
		$orderby=" order by createtime desc ";
		$type=$po['type']?:'';
		$sql="select a.* from pt_order_merge a ";
		$uid=$this->auth->id;
		$where=" where deletetime is null and user_id=$uid and is_follow=0 ";
		
		switch($type){
			case 'unpaid':
				$where.=" and `status`='unpaid' ";//参考 \app\admin\model\shopro\order\traits\OrderScope.php的 scopeUnpaid() 方法
				break;
			case 'nosend':
				$ziids=Db::name('shopro_order_item')
					->where('dispatch_status',0)
					->where('refund_status',0)
					->where('aftersale_status','in',[0,1])//未申请或者进行中的售后 参考 \app\admin\model\shopro\order\traits\OrderScope.php的 scopeNosend() 方法
					->column('order_id');
				$ziidstr=$ziids?implode(',',$ziids):'';
				$where.=" and ((`status` in ('paid','completed')) ";// or (pay_mode='offline' and `status`='pending') 不加了，用不着
				if($ziidstr) $where.=" and order_ids in ($ziidstr) ";
				$where.=") ";
				break;
			case 'noget':
				$ziids=Db::name('shopro_order_item')
					->where('dispatch_status',1)
					->where('refund_status',0)//参考 \app\admin\model\shopro\order\traits\OrderScope.php的 scopeNoget() 方法
					->column('order_id');
				$ziidstr=$ziids?implode(',',$ziids):'';
				$where.=" and ((`status` in ('paid','completed')) ";// or (pay_mode='offline' and `status`='pending') 不加了，用不着
				if($ziidstr) $where.=" and order_ids in ($ziidstr) ";
				$where.=") ";
				break;
			case 'nocomment':
				$ziids=Db::name('shopro_order_item')
					->where('dispatch_status',2)
					->where('refund_status',0)
					->where('comment_status',0)//参考 \app\admin\model\shopro\order\traits\OrderScope.php的 scopeNocomment() 方法
					->column('order_id');
				$ziidstr=$ziids?implode(',',$ziids):'';
				$where.=" and (`status` in ('paid','completed') ";
				if($ziidstr) $where.=" and order_ids in ($ziidstr) ";
				$where.=") ";
				break;
			case '2':
				$where.=" and `status` in (2,3,4)";
				break;
			case '3':
				$where.=" and `status` = 5 ";
				break;
			default:
				break;
		}
		$sql.=$where;
		$sql.=$orderby;
		$count=Db::name('order_merge')->query($sql);
		$total=count($count);
		$last_page=ceil($total/$size);
		$sql.=$limit;
		
		// echo $sql;die;
		
		$orders=Db::name('order_merge')->query($sql);
	  
        $orderModel = new OrderModel();
		$olists=[];
        $model = new \app\admin\model\paotui\Post();
        foreach ($orders as $ko=>&$o) {
            
			if($o['tb_name']=='shopro_order'){
				$order=$orderModel->with(['items', 'invoice'])->where('id',$o['order_ids'])->find();
				//  p($order->toArray());die;
				// $order=json_decode(json_encode($order),1);
				// p($ko);
			
				$order = $orderModel->setOrderItemStatusByOrder($order);
				
				$ptorder=db('paotui_post')->where('shopro_order_id',$order['id'])->find();
				if($ptorder){
				    $order['poster'] = Db::name('paotui_poster')->where(['id'=>['in',$v['poster_id']]])->field('id,poster_name,mobile')->select();
					$order['status_text']='跑腿单'.$this->psts[$ptorder['status']];
				}
				$order['ptorder']=$ptorder;
				$order['tb_type']=0;
				$olists[]=$order;
			}elseif($o['tb_name']=='paotui_post'){
				$v=$model->where('id',$o['order_ids'])->find();
				
				$v['tb_type']=1;
				$v['order_sn']=$v['order_no'];
				$v['from_or_to'] = ($v['user_id'] == $uid)?'from':'to';
                $v['poster'] = Db::name('paotui_poster')->where(['id'=>['in',$v['poster_id']]])->field('id,poster_name,mobile')->select();
                
				if($v['type'] == 2){
					$station = Db::name('station')->where(['id'=>$v['from_address_id']])->where('deletetime is null')->find();
					$school = Db::name('school')->where(['id'=>$station['school']])->find();
					$v['from_district'] = $school['name'];
					$v['from_poi'] = $station['name'];
					$v['from_address'] = $station['address'];
					$v['from_name'] = $station['name'];
					$v['from_mobile'] = '';
					
					//收件 用户
					$userschool = Db::name('user_school')->where(['id'=>$v['to_address_id']])->find();
					$building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
					$v['to_district'] = $school['name'];
					$v['to_poi'] = $building['name'];
					$v['to_address'] = $userschool['house_number'];
					$v['to_name'] = $userschool['nickname'];
					$v['to_mobile'] = $userschool['phone'];
					
					//取件码
					$codes  = Db::name('partition_code')->where(['paotui_post_id'=>$v['id']])->select();
					$codearr = [];
					foreach($codes as $kk=>$vv){
						//取件码分组
						$partition = Db::name('partition')->where(['id'=>$vv['partition_id']])->find();
						$station = Db::name('station')->where(['id'=>$partition['station_id']])->find();
						//整理取件码
						
						if($vv['partition_id'] == 0){
							$data2 = [
								'partition_name'=>'其他',
								'code'=>$vv['codes'],
							];
							$codearr[0]['data'][] =  $data2;
							$codearr[0]['name'] = '其他';
						}else{
							$data2 = [
								'partition_name'=>$partition['name'],
								'code'=>$vv['codes'],
							];
							$codearr[$station['id']]['data'][] =  $data2;
							$codearr[$station['id']]['name'] = $station['name'];
						}
						
						
					}
					$v['codearr'] = $codearr;
					
					$ptcode = Db::name('partition_code')->where(['paotui_post_id'=>$v['id'],'status'=>['in','1,2']])->find();
					if($ptcode){
						$v['codeastatus'] = 1;
					}else{
						$v['codeastatus'] = 0;
					}
					
				}
				if($v['type'] == 4){
					//收件 用户
					$userschool = Db::name('user_school')->where(['id'=>$v['from_address_id']])->find();
					$building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
					$school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
					$v['from_district'] = $school['name'];
					$v['from_poi'] = $building['name'];
					$v['from_address'] = $userschool['house_number'];
					$v['from_name'] = $userschool['nickname'];
					$v['from_mobile'] = $userschool['phone'];
				}
				if($v['type'] == 5){
					//收件 用户
					$userschool = Db::name('user_school')->where(['id'=>$v['to_address_id']])->find();
					$building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
					$school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
					$v['from_district'] = $school['name'];
					$v['from_poi'] = $building['name'];
					$v['from_address'] = $userschool['house_number'];
					$v['from_name'] = $userschool['nickname'];
					$v['from_mobile'] = $userschool['phone'];
				}
				$v['createtime']=date('Y-m-d H:i:s',$o['createtime']);
				$olists[]=$v;
			}
        }
		
		$data=[
			'data'=>$olists,
			'total'=>$total,
			'current_page'=>$current_page,
			'last_page'=>$last_page
		];

        $this->success('获取成功', $data);
    }

}
